/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.panels;

import data.Building;
import data.Resource;
import data.logic.BuildingSquareType;
import gui.MaiaWorld;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import maiaclient.interfaces.IResourceListener;

/**
 *
 * @author groep 11
 * @date 2007-2008
 */
public class BuildingFunctions extends JPanel implements IResourceListener {

    private JLabel lblImage;
    private JLabel lblName;
    private JLabel lblLevel;
    private JLabel lblLevelValue;
    private JLabel lblStrength;
    private JLabel lblStrengthValue;
    private JLabel lblCapacity;
    private JLabel lblCapacityValue;
    private JLabel lblStatus;
    private JLabel lblStatusValue;
    private JButton btnLevelUp;
    private JButton btnDestroy;
    private MaiaWorld parent;
    private JPanel pnlStandardButtons;
    private JPanel pnlBuildingButtons;
    private BuildingSquareType selectedBuildingSquareType;
    private Vector<Resource> resources;
    private ActionListener levelUpAction;
    private ActionListener destroyAction;
    private ActionListener buildAction;
    private JToggleButton selectedBuildButton;
    private ButtonGroup buildGroup;
    private Vector<JToggleButton> buildButtons;

    public BuildingFunctions(MaiaWorld parent) {


        this.parent = parent;
        this.parent.getMaia().addResourceListener(this);
        this.setBorder(BorderFactory.createEmptyBorder(10, 20, 0, 20));

        this.setLayout(new BorderLayout());
        lblImage = new JLabel();

        JPanel pnlInfo = new JPanel();
        pnlInfo.setLayout(new BoxLayout(pnlInfo, BoxLayout.PAGE_AXIS));
        lblName = new JLabel();
        lblName.setFont(new Font(lblName.getFont().getFontName(), Font.BOLD, 20));
        pnlInfo.add(lblName);

        JPanel pnlProperties = new JPanel(new GridLayout(0, 2));

        pnlProperties.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
        lblLevel = new JLabel("Level: ");
        lblLevel.setVisible(false);
        lblLevelValue = new JLabel();
        lblStrength = new JLabel("Strength: ");
        lblStrength.setVisible(false);
        lblStrengthValue = new JLabel();
        lblCapacity = new JLabel("Capacity: ");
        lblCapacity.setVisible(false);
        lblCapacityValue = new JLabel();
        lblStatus = new JLabel("Status: ");
        lblStatus.setVisible(false);
        lblStatusValue = new JLabel();

        lblLevelValue.setVisible(false);
        lblStrengthValue.setVisible(false);
        lblCapacityValue.setVisible(false);
        lblStatusValue.setVisible(false);

        pnlProperties.add(lblLevel);
        pnlProperties.add(lblLevelValue);
        pnlProperties.add(lblStrength);
        pnlProperties.add(lblStrengthValue);
        pnlProperties.add(lblStatus);
        pnlProperties.add(lblStatusValue);
        pnlProperties.add(lblCapacity);
        pnlProperties.add(lblCapacityValue);


        pnlInfo.add(pnlProperties);

        pnlStandardButtons = new JPanel();
        pnlStandardButtons.setLayout(new BoxLayout(pnlStandardButtons, BoxLayout.PAGE_AXIS));

        pnlBuildingButtons = new JPanel();
        pnlBuildingButtons.setLayout(new GridLayout(2, 3, 5, 5));
        pnlBuildingButtons.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));

        JPanel pnlButtons = new JPanel();
        pnlButtons.setLayout(new BorderLayout());
        pnlButtons.add(pnlStandardButtons, BorderLayout.WEST);
        pnlButtons.add(pnlBuildingButtons, BorderLayout.EAST);

        add(lblImage, BorderLayout.WEST);
        add(pnlInfo, BorderLayout.CENTER);
        add(pnlButtons, BorderLayout.EAST);
        try {
            parent.getMaia().requestResources();
        } catch (IOException ex) {
            Logger.getLogger(BuildingFunctions.class.getName()).log(Level.SEVERE, null, ex);
        }

        levelUpAction = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                levelUpBuilding();
            }
        };
        destroyAction = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                destructBuilding();
            }
        };

        buildAction = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setSelectedBuildButton((JToggleButton) e.getSource());
                BuildBuilding();
            }
        };
    }

    public void updateBuildingInfo(BuildingSquareType buildingSqTp) {

        if (selectedBuildingSquareType != null) {
            clearBuildingInfo();
        }
        selectedBuildingSquareType = buildingSqTp;
        // Info for all Buildings
        lblImage.setVisible(true);
        lblImage.setIcon(new ImageIcon(buildingSqTp.getImageUrl()));
        lblLevel.setVisible(true);
        lblLevelValue.setVisible(true);
        lblLevelValue.setText("" + buildingSqTp.getBuilding().getLevel());
        lblStrength.setVisible(true);
        lblStrengthValue.setVisible(true);
        lblStrengthValue.setText("" + buildingSqTp.getBuilding().getStrength());
        lblName.setVisible(true);
        lblName.setText(buildingSqTp.getBuilding().getName());

        pnlBuildingButtons.removeAll();
        pnlStandardButtons.removeAll();
        this.repaint();


        btnLevelUp = buildingSqTp.getBtnLevelUp();

        if (selectedBuildingSquareType.getBuilding().getMaxLevel() == selectedBuildingSquareType.getBuilding().getLevel()) {
            btnLevelUp.setEnabled(false);
        }
        if (selectedBuildingSquareType.getBuilding().getType() != 0) {
            if (selectedBuildingSquareType.getBuilding().getLevel() == parent.getMaia().getVillageLevel()) {
                btnLevelUp.setEnabled(false);
            } else {
                btnLevelUp.setEnabled(true);
            }
        }
        btnLevelUp.addActionListener(levelUpAction);
        pnlStandardButtons.add(btnLevelUp);

        //Set specific info invisible 
        lblCapacityValue.setVisible(false);
        lblCapacity.setVisible(false);
        lblStatus.setVisible(false);
        lblStatusValue.setVisible(false);

        // 0 means it's a Town Center Type
        // 1 => ProductionBuilding
        // 2 => Military Building
        if (buildingSqTp.getBuilding().getType() == 0) {

            buildGroup = new ButtonGroup();
            buildButtons = buildingSqTp.getBuildButtons(parent.getMaia().getVillageLevel());

            for (JToggleButton buildButton : buildButtons) {
                buildButton.addActionListener(buildAction);
                pnlBuildingButtons.add(buildButton);
                buildGroup.add(buildButton);

            }

        } else if (buildingSqTp.getBuilding().getType() == 1) {

            lblStatus.setVisible(true);
            lblStatusValue.setVisible(true);
            lblStatusValue.setText(buildingSqTp.getBuilding().getStatusDescription());
            lblCapacityValue.setVisible(true);
            lblCapacity.setVisible(true);
            lblCapacityValue.setText(buildingSqTp.getBuilding().getCapacity() + " " + buildingSqTp.getBuilding().getResourceType());
            pnlStandardButtons.add(Box.createVerticalStrut(10));
            btnDestroy = buildingSqTp.getBtnDestroy();
            btnDestroy.addActionListener(destroyAction);
            pnlStandardButtons.add(btnDestroy);


        } else if (buildingSqTp.getBuilding().getType() == 2) {

            lblStatus.setVisible(true);
            lblStatusValue.setVisible(true);
            lblStatusValue.setText(buildingSqTp.getBuilding().getStatusDescription());
            pnlStandardButtons.add(Box.createVerticalStrut(10));
            btnDestroy = buildingSqTp.getBtnDestroy();
            btnDestroy.addActionListener(destroyAction);
            pnlStandardButtons.add(btnDestroy);
        }

    }

    public boolean upgradeAble(int foodCost, int woodCost, int ironCost, int stoneCost, int goldCost) {
        boolean upgradeAble = true;

        for (Resource resource : this.resources) {

            if (resource.getResourceTypeName().equals("Food")) {
                if (foodCost > resource.getAmount()) {
                    upgradeAble = false;
                }
            }
            if (resource.getResourceTypeName().equals("Wood")) {
                if (woodCost > resource.getAmount()) {
                    upgradeAble = false;
                }
            }
            if (resource.getResourceTypeName().equals("Iron")) {
                if (ironCost > resource.getAmount()) {
                    upgradeAble = false;
                }
            }
            if (resource.getResourceTypeName().equals("Stone")) {
                if (stoneCost > resource.getAmount()) {
                    upgradeAble = false;
                }
            }
            if (resource.getResourceTypeName().equals("Gold")) {
                if (goldCost > resource.getAmount()) {
                    upgradeAble = false;
                }
            }
        }
        return upgradeAble;

    }

    public void updateResources(int foodCost, int woodCost, int ironCost, int stoneCost, int goldCost) {
        try {

            // Update resources
            for (Resource resource : this.resources) {
                if (resource.getResourceTypeName().equals("Food")) {
                    if (foodCost != -1) {
                        resource.setAmount(resource.getAmount() - foodCost);
                    }
                }
                if (resource.getResourceTypeName().equals("Wood")) {
                    if (woodCost != -1) {
                        resource.setAmount(resource.getAmount() - woodCost);
                    }
                }
                if (resource.getResourceTypeName().equals("Iron")) {
                    if (ironCost != -1) {
                        resource.setAmount(resource.getAmount() - ironCost);
                    }
                }
                if (resource.getResourceTypeName().equals("Stone")) {
                    if (stoneCost != -1) {
                        resource.setAmount(resource.getAmount() - stoneCost);
                    }
                }
                if (resource.getResourceTypeName().equals("Gold")) {
                    if (goldCost != -1) {
                        resource.setAmount(resource.getAmount() - goldCost);
                    }
                }
            }

            parent.getMaia().editResources(resources);
        } catch (IOException ex) {
            Logger.getLogger(BuildingFunctions.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void levelUpBuilding() {

        int foodCost = -1;
        String sFoodCost = "";
        int woodCost = -1;
        String sWoodCost = "";
        int ironCost = -1;
        String sIronCost = "";
        int stoneCost = -1;
        String sStoneCost = "";
        int goldCost = -1;
        String sGoldCost = "";

        Building building = selectedBuildingSquareType.getBuilding();
        if (building.getFoodCost() != -1) {
            foodCost = building.getFoodCost() * building.getLevel();
        }
        if (building.getWoodCost() != -1) {
            woodCost = building.getWoodCost() * building.getLevel();
        }
        if (building.getIronCost() != -1) {
            ironCost = building.getIronCost() * building.getLevel();
        }
        if (building.getStoneCost() != -1) {
            stoneCost = building.getStoneCost() * building.getLevel();
        }
        if (building.getGoldCost() != -1) {
            goldCost = building.getGoldCost() * building.getLevel();
        }

        if (upgradeAble(foodCost, woodCost, ironCost, stoneCost, goldCost)) {
            try {

                // Setting capacity higher
                if (building.getCapacity() != -1) {
                    //building.setCapacity(building.getCapacity() + );
                    double increase = (double) building.getCapacity() / (double) building.getLevel() * 2.05;
                    int increaseRounded = building.getCapacity() + (int) increase;

                    building.setCapacity(increaseRounded);
                }
                // Settings Strength Higher
                building.setStrength(building.getStrength() + 100);

                // Setting Level Higher
                building.setLevel(building.getLevel() + 1);

                // Update resources
                updateResources(foodCost, woodCost, ironCost, stoneCost, goldCost);

                // Update Database
                parent.getMaia().levelUpBuilding(building);



                // When we upgrade Town Center we need to set VillageLevel 
                if (building.getType() == 0) {
                    parent.getMaia().setVillageLevel(parent.getMaia().getVillageLevel() + 1);
                }

                // update BuildingInfo
                selectedBuildingSquareType.setBuilding(building);
                updateBuildingInfo(selectedBuildingSquareType);

            } catch (IOException ex) {
                Logger.getLogger(BuildingFunctions.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {

            if (foodCost != -1) {
                sFoodCost = foodCost + " Food ";
            }
            if (woodCost != -1) {
                sWoodCost = woodCost + " Wood ";
            }
            if (stoneCost != -1) {
                sStoneCost = stoneCost + " Stone ";
            }
            if (ironCost != -1) {
                sIronCost = ironCost + " Iron ";
            }
            if (goldCost != -1) {
                sGoldCost = goldCost + " Gold";
            }

            JOptionPane.showMessageDialog(parent, "You don't have enough resources to upgrade your building." +
                    " You need: " + sFoodCost + sWoodCost + sStoneCost + sIronCost + sGoldCost + ".");
        }

    }

    public void destructBuilding() {
        if (JOptionPane.showConfirmDialog(parent, "Are you sure you want to delete this building?",
                "Delete Building?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            try {
                // Delete building in Database
                parent.getMaia().destructBuilding(selectedBuildingSquareType.getBuilding().getBuildingId());
                // Update World
                parent.getPnlVillageMap().destructBuilding(selectedBuildingSquareType);
                // unselect Building
                clearBuildingInfo();
            } catch (IOException ex) {
                Logger.getLogger(BuildingFunctions.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }

    public void BuildBuilding() {

        System.out.println(getSelectedBuildButton().getActionCommand());

    }

    public void clearBuildingInfo() {

        lblImage.setVisible(false);
        lblLevel.setVisible(false);
        lblStrength.setVisible(false);
        lblCapacity.setVisible(false);
        lblStatus.setVisible(false);
        lblName.setVisible(false);

        lblLevelValue.setVisible(false);
        lblStrengthValue.setVisible(false);
        lblCapacityValue.setVisible(false);
        lblStatusValue.setVisible(false);


        if (btnLevelUp != null) {
            btnLevelUp.removeActionListener(levelUpAction);
        }
        if (btnDestroy != null) {
            btnDestroy.removeActionListener(destroyAction);
        }
        pnlStandardButtons.removeAll();
        pnlBuildingButtons.removeAll();

        selectedBuildingSquareType = null;
        setSelectedBuildButton(null);
        if (buildGroup != null) {
            buildGroup.clearSelection();
        }

        if (buildButtons != null) {
            for (JToggleButton buildbutton : buildButtons) {
                buildbutton.removeActionListener(buildAction);
            }
        }
    }

    public void updateResources(Vector<Resource> resources) {
        this.resources = resources;
    }

    public JToggleButton getSelectedBuildButton() {
        return selectedBuildButton;
    }

    public void setSelectedBuildButton(JToggleButton selectedBuildButton) {
        this.selectedBuildButton = selectedBuildButton;
    }
}
